package com.ukao.cashregister.ui.stokin;


import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ukao.cashregister.R;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.BalanceBean;
import com.ukao.cashregister.bean.PayInfoBean;
import com.ukao.cashregister.bean.UserInfoBean;
import com.ukao.cashregister.dialog.QuiltSweepDialogFragment;
import com.ukao.cashregister.dialog.TradeDialodFragment;
import com.ukao.cashregister.eventbus.MembershipCardEvent;
import com.ukao.cashregister.eventbus.PayAmountEvent;
import com.ukao.cashregister.eventbus.PayEvent;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.pesenter.QuiltSweepPesenter;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.KeyBoardUtil;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.QuiltSweepView;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.Unbinder;


import static com.ukao.cashregister.R.id.payment_code;
import static com.ukao.cashregister.eventbus.PayEvent.Message.PAY_SUCCEED;

/**
 * 支付宝支付和微信支付
 */
public class AlipayWeChatFragment extends MvpFragment<QuiltSweepPesenter> implements QuiltSweepView {


    @BindView(R.id.by_sweep)
    RadioButton bySweep;
    Unbinder unbinder;
    @BindView(R.id.left_layout)
    ImageView leftLayout;
    @BindView(R.id.right_layout)
    ImageView rightLayout;

    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(payment_code)
    EditText etInputCode;
    @BindView(R.id.main_sweep_layout)
    LinearLayout mainSweepLayout;
    @BindView(R.id.rb_main_sweep)
    RadioButton mainSweep;
    @BindView(R.id.layout)
    LinearLayout layout;

    private int entertype;

    private Handler mHandler = new Handler();
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private PayInfoBean mPayInfo;
    private boolean loadfinish = false;
    private String orderId;
    private String seq;
    private String balance = "";
    private String shouldPice = "";
    private String codeUrl;
    private QuiltSweepDialogFragment mQuiltSweep;
    private String userId;
    private String rechargeAmount;
    private String withActive;

    public static AlipayWeChatFragment newInstance(int entertype, String isEnableAli, String rechargeAmount, String withActive) {
        AlipayWeChatFragment fragment = new AlipayWeChatFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, entertype);
        args.putString(ARG_PARAM2, isEnableAli);
        args.putString(ARG_PARAM3, rechargeAmount);
        args.putString(ARG_PARAM4, withActive);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            entertype = getArguments().getInt(ARG_PARAM1);
            userId = getArguments().getString(ARG_PARAM2);/*充值*/
            rechargeAmount = getArguments().getString(ARG_PARAM3);/*充值*/
            withActive = getArguments().getString(ARG_PARAM4);/*充值*/
        }
    }

    @Override
    protected QuiltSweepPesenter createPresenter() {
        return new QuiltSweepPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_alipay_we_chat, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {
        super.initListener();
        etInputCode.setOnEditorActionListener(mOnEditorActionListener);

    }

    TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                String strPaymentCode = getText(etInputCode);
                if (!strPaymentCode.isEmpty()) {
                    switch (entertype) {   /*主扫*/
                        case 0: /*支付宝*/
                            if (!CheckUtils.isEmpty(userId)) {  /*充值*/
                                mvpPresenter.wxAirectMicroRecharge(strPaymentCode, userId, rechargeAmount, withActive, false, true);
                            } else if (mPayInfo != null) {
                                mvpPresenter.wxMicroPay(orderId, balance, strPaymentCode, false, mPayInfo.isUseUPay(), mPayInfo.getCpnRelId());
                            }
                            break;
                        case 1:/*微信*/
                            if (!CheckUtils.isEmpty(userId)) {  /*充值*/
                                mvpPresenter.wxAirectMicroRecharge(strPaymentCode, userId, rechargeAmount, withActive, true, true);
                            } else if (mPayInfo != null) {
                                mvpPresenter.wxMicroPay(orderId, balance, strPaymentCode, true, mPayInfo.isUseUPay(), mPayInfo.getCpnRelId());
                            }

                            break;
                    }
                    etInputCode.setText("");
                    KeyBoardUtil.hideInputmethod(etInputCode);
                    return true;
                }


            }
            return false;
        }
    };

    @Override
    protected boolean useEventBus() {
        return true;
    }


            @Subscribe
            public void onEvent(PayAmountEvent event) {
                switch (event.getMessage()) {
                    case recharge: /*充值信息*/
                        loadfinish = false;/*重新生成二維碼*/
                        HashMap mHashMap = (HashMap) event.getData();
                        rechargeAmount = (String) mHashMap.get(ARG_PARAM1);
                        withActive = (String) mHashMap.get(ARG_PARAM2);
                        break;
                    case PAY_COUNT:  //获得支付信息数据
                        mPayInfo = (PayInfoBean) event.getData();
                        balance = String.valueOf(mPayInfo.getPayBalance());
                        shouldPice = CheckUtils.isEmptyNumber(mPayInfo.getShouldPrice());
                        orderId = mPayInfo.getOrderId();
                break;


        }
    }


    @OnCheckedChanged({R.id.rb_main_sweep, R.id.by_sweep})
    public void OnCheckedChanged(CompoundButton view, boolean check) {
        if (check) {
            switch (view.getId()) {
                case R.id.rb_main_sweep:
                    showSelectBackground(true);
                    break;
                case R.id.by_sweep:
                    showSelectBackground(false);
                    switch (entertype) {
                        case 0: /*支付宝*/
                            if (!loadfinish) {
                                if (!CheckUtils.isEmpty(userId)) {  /*充值*/
                                    mvpPresenter.quiltRecharge(userId, rechargeAmount, withActive, false);
                                } else if (mPayInfo != null) {
                                    mvpPresenter.wxUnifiedOrder(orderId, balance, false, mPayInfo.isUseUPay(), mPayInfo.getCpnRelId());
                                }

                            } else {
                                showQuiltSweepDialog();
                            }
                            break;
                        case 1:/*微信*/
                            if (!loadfinish) {
                                if (!CheckUtils.isEmpty(userId)) {    /*充值*/
                                    mvpPresenter.quiltRecharge(userId, rechargeAmount, withActive, true);
                                } else if (mPayInfo != null) {
                                    mvpPresenter.wxUnifiedOrder(orderId, balance, true, mPayInfo.isUseUPay(), mPayInfo.getCpnRelId());
                                }


                            } else {
                                showQuiltSweepDialog();
                            }


                            break;
                    }


                    break;
            }
        }

    }

    public void showSelectBackground(boolean isAlipay) {
        if (isAlipay) {
            mainSweepLayout.setVisibility(View.VISIBLE);
            leftLayout.setVisibility(View.VISIBLE);
            rightLayout.setVisibility(View.INVISIBLE);

        } else {
            mainSweepLayout.setVisibility(View.GONE);
            leftLayout.setVisibility(View.INVISIBLE);
            rightLayout.setVisibility(View.VISIBLE);
        }

    }


    @Override
    public void loadQRCodeData(BalanceBean mBalance) {
        loadfinish = true;
        seq = mBalance.getSeq();
        codeUrl = mBalance.getCodeUrl();
        showQuiltSweepDialog();
        postDelayedquery();
    }

    @Override
    public void scanPayMicroFail(String msg) {
        T.show(msg);
        mainSweep.setChecked(true);
    }

    public void showQuiltSweepDialog() {
        if (CheckUtils.isNull(codeUrl)) return;
        mQuiltSweep = new QuiltSweepDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM1, codeUrl);
        bundle.putString(ARG_PARAM2, CheckUtils.isEmpty(rechargeAmount) ? shouldPice : rechargeAmount);
        bundle.putInt(ARG_PARAM4, entertype);
        mQuiltSweep.setOnSureClickListener(mOnDialogSureClick);
        mQuiltSweep.setArguments(bundle);
        mQuiltSweep.show(getChildFragmentManager(), QuiltSweepDialogFragment.class.getName());
    }

    private OnDialogSureClickListener mOnDialogSureClick = new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            if (CheckUtils.isNull(mainSweep)) return;
            mainSweep.setChecked(true);
            if (!CheckUtils.isEmpty(orderId)) {
                mvpPresenter.unlockOrder(orderId);
            }
        }
    };


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisible = true;
        postDelayedquery();

    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        KeyBoardUtil.hideInputmethod(etInputCode);
        isVisible = false;
        removeCallbacks();
    }


    public void postDelayedquery() {
        if (loadfinish && isVisible)
            mHandler.postDelayed(mRunnable, 2000);
    }

    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {

            mvpPresenter.queryStatusBySeq(seq);

        }
    };

    public void removeCallbacks() {
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void loadFail(String msg) {
        T.show(msg);
    }

    @Override
    public void queryStatusData(BalanceBean mBalance) {
        switch (mBalance.getStatus()) {
            case -1:
                mQuiltSweep.dismiss();
                removeCallbacks();
                T.show("交易失败");
                break;
            case 0: /*status -1.交易失败 0.交易中 1.交易成功*/

                removeCallbacks();
                postDelayedquery();
                break;
            case 1:
                mQuiltSweep.dismiss();
                removeCallbacks();
                PayEvent.postNoData(PAY_SUCCEED);
                break;


        }
    }

    @Override
    public void unlockOrderData() {
        loadfinish = false;
    }

    @Override
    public void unlockOrderFail() {
        loadfinish = false;
    }

    @Override
    public void loadPayData(String msg) {
        KeyBoardUtil.hideInputmethod(etInputCode);
        dismissProgressDialog();
        PayEvent.postNoData(PAY_SUCCEED);
    }


    /**
     * 充值支付主扫返回结果
     *@param tradeSeq  交易流水号
     * @param mBalanceBean
     */
    @Override
    public void userRechargeData(BalanceBean mBalanceBean,String tradeSeq) {
        switch (mBalanceBean.getStatus()) {
            case 1://     交易成功
                dismissProgressDialog();
                PayEvent.postNoData(PAY_SUCCEED);
                break;
            case -1://     交易失败
                showTradeDialog(tradeSeq,"交易失败");
                break;
            case 0://     交易中
                showTradeDialog(tradeSeq,"交易中");
                break;
        }


    }


    /**
     * 获取充值的用户数据
     * @param mUserInfoBean
     */
    @Override
    public void userinfoSucced(final UserInfoBean.UserBean mUserInfoBean) {
        PayEvent.postHasData(PayEvent.Message.look_use,mUserInfoBean);

    }



    public void showTradeDialog(String tradeSeq,String  error) {
        TradeDialodFragment mTradeDialog=TradeDialodFragment.newInstance(tradeSeq,error);
        mTradeDialog.setOnSureClickListener(mOnDialogSureClickListener);
        mTradeDialog.show(getChildFragmentManager(),TradeDialodFragment.class.getName());
    }

    private   OnDialogSureClickListener  mOnDialogSureClickListener=new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            switch ((int)message) {
                case R.id.back_home_btn://     返回主页
                    MembershipCardEvent.postNoData(MembershipCardEvent.Message.back_home);
                    break;
                case R.id.look_use_btn://     查看该用户
                    mvpPresenter.userinfoData(userId);
                    break;
            }
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        hideLoading();
        removeCallbacks();
    }
}
